﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace GetListIDs
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Validates SiteURL entered by user
        /// </summary>
        /// <returns>True if the URL is provided, False otherwise</returns>
        private bool ValidateSiteURL()
        {
            if (txtSiteURL.Text.Trim().Equals(string.Empty))
            {
                MessageBox.Show("Please provide the site url to proceed");
                return false;
            }

            return true;
        }

        /// <summary>
        /// Performs a lookup for all the lists and respective IDs for the provided SiteURL
        /// </summary>
        /// <param name="sender">General Param</param>
        /// <param name="e">General Param</param>
        private void btnBrowseSite_Click(object sender, EventArgs e)
        {
            if (ValidateSiteURL())
            {
                btnBrowseSite.Enabled = false;
                SPDataLayer SPDataLayerInstance = new SPDataLayer();
                Uri siteURL = new Uri(txtSiteURL.Text.Trim());

                pbStatus.MarqueeAnimationSpeed = 100;

                List<Microsoft.SharePoint.Client.List> SiteLists = SPDataLayerInstance.GetLists(siteURL);
                if (SiteLists != null)
                {
                    DataTable dtListInfo = new DataTable("List Info");
                    dtListInfo.Columns.Add("List");
                    dtListInfo.Columns.Add("ListID");

                    foreach (Microsoft.SharePoint.Client.List currentList in SiteLists)
                    {
                        pbStatus.Refresh();
                        DataRow newListInfoRow = dtListInfo.NewRow();
                        newListInfoRow["List"] = currentList.Title;
                        newListInfoRow["ListID"] = currentList.Id;
                        dtListInfo.Rows.Add(newListInfoRow);
                    }
                    pbStatus.Value = pbStatus.Maximum;
                    dgvResult.DataSource = dtListInfo;
                    dgvResult.Refresh();
                }
                else
                {
                    MessageBox.Show("Error occurred. Please try again ...");
                }

                pbStatus.MarqueeAnimationSpeed = 0;
                pbStatus.Value = pbStatus.Minimum;
                btnBrowseSite.Enabled = true;
            }
        }
    }
}